package cn.easybuy.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory factory;
    private MyBatisUtil(){}
    static{//在静态代码块下，factory只被创建一次
        InputStream is= null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        factory=new SqlSessionFactoryBuilder().build(is);
    }
    //创建SqlSession对象
    public static SqlSession createSqlSession(){
        return factory.openSession(false);//默认为true（自动提交）；
    }
    //关闭SqlSession对象
    public static void closeSqlSession(SqlSession sqlSession){
        if(null!=sqlSession)
            sqlSession.close();
    }
}
